<template>
  <div class="login-container">
    <van-nav-bar title="黑马头条 - 登录" fixed> </van-nav-bar>

    <!-- 登录的表单 -->
    <van-form @submit="login">
      <van-field
        v-model="form.mobile"
        type="tel"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="rules.mobile"
      ></van-field>
      <van-field
        v-model="form.code"
        type="password"
        label="登录密码"
        placeholder="请输入登录密码"
        required
        :rules="rules.code"
      ></van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from "@/api/UserAPI";
import { mapMutations } from "vuex";
export default {
  name: "Login",
  data() {
    return {
      form: {
        mobile: "",
        code: "",
      },
      // 表单的校验规则对象
      rules: {
        // 手机号的校验规则
        mobile: [
          { required: true, message: "请填写您的手机号", trigger: "onBlur" },
          {
            pattern: /^1\d{10}$/,
            message: "请填写正确的手机号",
            trigger: "onBlur",
          },
        ],
        // 密码的校验规则
        code: [
          { required: true, message: "请填写您的密码", trigger: "onBlur" },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(["updateTokenInfo"]),

    async login() {
      // console.log("ok");
      // 发送请求
      const { data: ret } = await loginAPI(this.form);
      console.log(ret.data);
      if (ret.message == "OK") {
        // 把toKen保存到vuex
        this.updateTokenInfo(ret.data);
        // 跳转到主页
        this.$router.push("/");
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  padding-top: 46px;
}

.van-form {
  margin-top: 5.3333rem;
}
</style>
